package General;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadService {
	private static ThreadService instance = new ThreadService();
	private ThreadPoolExecutor tpeAnalysis = (ThreadPoolExecutor) Executors
			.newFixedThreadPool(10, new AnalysisThreadFactory());
	private ThreadPoolExecutor tpeCollection = (ThreadPoolExecutor) Executors
			.newFixedThreadPool(10, new CollectionThreadFactory());

	private ThreadService() {
	}

	public static ThreadService getInstance() {
		return instance;
	}

	public ThreadPoolExecutor getAnalysisThreadPoolExecutor() {
		return tpeAnalysis;
	}

	public ThreadPoolExecutor getCollectionThreadPoolExecutor() {
		return tpeCollection;
	}

	class CollectionThreadFactory implements ThreadFactory {
		@Override
		public Thread newThread(Runnable r) {
			Thread t = new Thread(r);
			t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
				@Override
				public void uncaughtException(Thread t, Throwable e) {
					if(e instanceof IOException) {
						System.out.println("caught IOE");
					}
				}
			});

			return t;
		}
	}

	class AnalysisThreadFactory implements ThreadFactory {
		@Override
		public Thread newThread(Runnable r) {
			Thread t = new Thread(r);
			t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
				@Override
				public void uncaughtException(Thread t, Throwable e) {
					// output?
					// logger?
					if (e instanceof NullPointerException) {
						System.out.println("caught NPE");
					}
				}
			});

			return t;
		}
	}
}
